package com.example.issue.network

import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.*

object ApiClient {
    private var token: String? = null

    fun setToken(t: String?) { token = t }

    private val auth = Interceptor { chain ->
        val req = chain.request().newBuilder().apply {
            token?.let { header("Authorization", "Bearer $it") }
        }.build()
        chain.proceed(req)
    }

    private val http = OkHttpClient.Builder().addInterceptor(auth).build()

    private val retrofit = Retrofit.Builder()
        .baseUrl(System.getenv("API_BASE") ?: "http://10.0.2.2:8000")
        .client(http)
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    val api: Api by lazy { retrofit.create(Api::class.java) }
}

interface Api {
    data class Token(val access_token: String)
    data class LoginIn(val email: String, val password: String)
    data class User(val id: Int, val email: String, val name: String)
    data class Issue(val id: Int, val title: String, val description: String?, val status: String, val priority: String)

    @POST("/api/auth/login")
    suspend fun login(@Body body: LoginIn): Token

    @GET("/api/users/me")
    suspend fun me(): User

    @GET("/api/issues")
    suspend fun issues(@Query("status") status: String? = null): List<Issue>
}
